/* NOTICE
    OpenJaWS - Open Java Weather Station
    
    Copyright (C) 2008 Grant Gardner <grant@lastweekend.com.au>
    
    OpenJaWS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
NOTICE */

package au.com.lastweekend.openjaws.web;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;

import au.com.lastweekend.openjaws.api.WeatherStationConfigurer;
import au.com.lastweekend.openjaws.api.WeatherStationException;

@Controller
@RequestMapping("/stationConfig.do")
@SessionAttributes("config")
public class StationConfigurationController {

    private static final Logger LOG = LoggerFactory.getLogger(StationConfigurationController.class);
    public static final Class<?> SPRING_CLASS = StationConfigurationController.class;
    private WeatherStationConfigurer config;

    @Autowired
    public StationConfigurationController(WeatherStationConfigurer config) {

        this.config = config;
    }

    @RequestMapping(method = RequestMethod.GET)
    public String getForm(ModelMap mm) {

        LOG.info("Displaying");
        mm.addAttribute("config", config);
        mm.addAttribute("errors", 0);
        return config.getFormName();

    }

    @RequestMapping(method = RequestMethod.POST)
    public String submitForm(@ModelAttribute("config")
    WeatherStationConfigurer config, BindingResult bindingResult, ModelMap mm) throws WeatherStationException {

        LOG.info("Saving");
        config.save();
        mm.addAttribute("config", config);
        mm.addAttribute("errors", bindingResult.getErrorCount());
        return config.getFormName();

    }
}
